# -*- coding: utf-8 -*-
# File : sell_service.py
# Author: taoyahui
# Date : 2021/10/17
from config import contract_name, contract_address, contract_abi
from utils import common_utils, id_utils
from models.order import Order
from services import user_service
import json
from results import *
from models.create_order import CreateOrder


def create_order(json_dict, request):
    get_user_res = user_service.get_user_by_token(request)
    if get_user_res['code'] != 200:
        return json.dumps(get_user_res,ensure_ascii=False)
    user = get_user_res['data']
    num = json_dict['num']
    food_id = json_dict['food_id']
    price = json_dict['price']
    order_no = next(id_utils.unique_sequence)
    res = common_utils.common_bc_req(user.address, 'FoodTraceNew', 'createOrder', [order_no, num, food_id, price], contract_address,
                                     contract_abi)
    if res.status_code == 200:
        res_json = json.loads(res.text)
        if res_json['status'] == '0x0':
            return success_result
        else:
            return gen_result(500, res_json['message'])
    else:
        return gen_result(res.status_code, res.text)


def get_order(json_dict, request):
    get_user_res = user_service.get_user_by_token(request)
    if get_user_res['code'] != 200:
        return json.dumps(get_user_res, ensure_ascii=False)
    user = get_user_res['data']
    order_no = json_dict['order_no']
    res = common_utils.common_bc_req(user.address, contract_name, 'getOrder', [order_no],
                                     contract_address,
                                     contract_abi)
    if res.status_code == 200:
        order_arr = json.loads(res.text)
        order = Order(order_arr[0], order_arr[1], order_arr[2], order_arr[3], order_arr[4], common_utils.get_time(order_arr[5]))
        return gen_result('200', order.__dict__)
    else:
        return gen_result(res.status_code, res.text)


def query_order(json_dict):
    page = json_dict['page']
    if 'order_no' in json_dict:
        trans_list = CreateOrder.query.filter_by(order_no=json_dict['order_no']).order_by(CreateOrder.pk_id.desc()).paginate(page, per_page=10,
                                                                                   error_out=False).items
    else:
        trans_list = CreateOrder.query.order_by(CreateOrder.pk_id.desc()).paginate(page, per_page=10, error_out=False).items
    trans_list = [item.to_json() for item in trans_list]
    total = CreateOrder.query.count()
    return gen_result('200', {
        'total':total,
        'list':trans_list
    })